package org.example.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.example.backend.constant.ResultCode;
import org.example.backend.dto.PageResult;
import org.example.backend.dto.Result;
import org.example.backend.entity.DeliveryRoute;
import org.example.backend.entity.DeliveryRouteItem;
import org.example.backend.entity.Leader;
import org.example.backend.exception.BusinessException;
import org.example.backend.mapper.DeliveryRouteItemMapper;
import org.example.backend.mapper.DeliveryRouteMapper;
import org.example.backend.mapper.LeaderMapper;
import org.example.backend.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 配送路线控制器
 * 提供配送路线查询、新增、修改、删除等功能
 */
@RestController
@RequestMapping("/delivery-route")
public class DeliveryRouteController {

    @Autowired
    private DeliveryRouteMapper deliveryRouteMapper;
    
    @Autowired
    private DeliveryRouteItemMapper deliveryRouteItemMapper;
    
    @Autowired
    private LeaderMapper leaderMapper;

    /**
     * 分页查询配送路线列表
     * @param current 当前页码
     * @param size 每页大小
     * @param name 路线名称（可选，模糊查询）
     * @param status 状态（可选，精确查询）
     * @return 分页结果
     */
    @GetMapping("/page")
    public ResponseEntity<Result<PageResult<DeliveryRoute>>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status) {
        
        Page<DeliveryRoute> page = new Page<>(current, size);
        
        LambdaQueryWrapper<DeliveryRoute> queryWrapper = Wrappers.<DeliveryRoute>lambdaQuery()
                .like(StringUtils.isNotBlank(name), DeliveryRoute::getName, name)
                .eq(status != null, DeliveryRoute::getStatus, status)
                .orderByDesc(DeliveryRoute::getCreateTime);
        
        Page<DeliveryRoute> routePage = deliveryRouteMapper.selectPage(page, queryWrapper);
        
        return ResponseUtil.success(new PageResult<>(routePage.getTotal(), routePage.getRecords()));
    }
    
    /**
     * 获取所有可用配送路线
     * @return 配送路线列表
     */
    @GetMapping("/list")
    public ResponseEntity<Result<List<DeliveryRoute>>> list() {
        List<DeliveryRoute> routes = deliveryRouteMapper.selectList(
                Wrappers.<DeliveryRoute>lambdaQuery()
                        .eq(DeliveryRoute::getStatus, 1)
                        .orderByDesc(DeliveryRoute::getCreateTime)
        );
        return ResponseUtil.success(routes);
    }
    
    /**
     * 获取配送路线详情
     * @param id 路线ID
     * @return 路线详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<Map<String, Object>>> getById(@PathVariable Long id) {
        DeliveryRoute route = deliveryRouteMapper.selectById(id);
        if (route == null) {
            return ResponseUtil.notFound("配送路线不存在");
        }
        
        // 查询路线明细
        List<DeliveryRouteItem> items = deliveryRouteItemMapper.selectList(
                Wrappers.<DeliveryRouteItem>lambdaQuery()
                        .eq(DeliveryRouteItem::getRouteId, id)
                        .orderByAsc(DeliveryRouteItem::getSequence)
        );
        
        // 查询团长信息
        List<Map<String, Object>> itemsWithLeader = new ArrayList<>();
        for (DeliveryRouteItem item : items) {
            Leader leader = leaderMapper.selectById(item.getLeaderId());
            if (leader != null) {
                Map<String, Object> itemMap = new HashMap<>();
                itemMap.put("id", item.getId());
                itemMap.put("leaderId", item.getLeaderId());
                itemMap.put("leaderName", leader.getName());
                itemMap.put("leaderPhone", leader.getPhone());
                itemMap.put("leaderAddress", leader.getAddress());
                itemMap.put("sequence", item.getSequence());
                itemsWithLeader.add(itemMap);
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("route", route);
        result.put("items", itemsWithLeader);
        
        return ResponseUtil.success(result);
    }
    
    /**
     * 新增配送路线
     * @param routeMap 路线信息
     * @return 操作结果
     */
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Void>> save(@Valid @RequestBody Map<String, Object> routeMap) {
        // 获取路线基本信息
        String name = (String) routeMap.get("name");
        String description = (String) routeMap.get("description");
        Integer status = (Integer) routeMap.get("status");
        List<Map<String, Object>> items = (List<Map<String, Object>>) routeMap.get("items");
        
        // 检查路线名称是否已存在
        Long count = deliveryRouteMapper.selectCount(Wrappers.<DeliveryRoute>lambdaQuery().eq(DeliveryRoute::getName, name));
        if (count > 0) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "路线名称已存在");
        }
        
        // 创建路线
        DeliveryRoute route = new DeliveryRoute();
        route.setName(name);
        route.setDescription(description);
        route.setStatus(status);
        deliveryRouteMapper.insert(route);
        
        // 创建路线明细
        if (items != null && !items.isEmpty()) {
            for (int i = 0; i < items.size(); i++) {
                Map<String, Object> item = items.get(i);
                Long leaderId = Long.valueOf(item.get("leaderId").toString());
                
                // 检查团长是否存在
                Leader leader = leaderMapper.selectById(leaderId);
                if (leader == null) {
                    throw new BusinessException(ResultCode.DATA_NOT_EXISTED, "团长不存在：ID=" + leaderId);
                }
                
                DeliveryRouteItem routeItem = new DeliveryRouteItem();
                routeItem.setRouteId(route.getId());
                routeItem.setLeaderId(leaderId);
                routeItem.setSequence(i + 1);
                deliveryRouteItemMapper.insert(routeItem);
            }
        }
        
        return ResponseUtil.created();
    }
    
    /**
     * 修改配送路线
     * @param routeMap 路线信息
     * @return 操作结果
     */
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Void>> update(@Valid @RequestBody Map<String, Object> routeMap) {
        // 获取路线基本信息
        Long id = Long.valueOf(routeMap.get("id").toString());
        String name = (String) routeMap.get("name");
        String description = (String) routeMap.get("description");
        Integer status = (Integer) routeMap.get("status");
        List<Map<String, Object>> items = (List<Map<String, Object>>) routeMap.get("items");
        
        // 检查路线是否存在
        DeliveryRoute existRoute = deliveryRouteMapper.selectById(id);
        if (existRoute == null) {
            return ResponseUtil.notFound("配送路线不存在");
        }
        
        // 检查路线名称是否已被其他路线使用
        if (!existRoute.getName().equals(name)) {
            Long count = deliveryRouteMapper.selectCount(
                    Wrappers.<DeliveryRoute>lambdaQuery()
                            .eq(DeliveryRoute::getName, name)
                            .ne(DeliveryRoute::getId, id)
            );
            if (count > 0) {
                throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "路线名称已存在");
            }
        }
        
        // 更新路线
        DeliveryRoute route = new DeliveryRoute();
        route.setId(id);
        route.setName(name);
        route.setDescription(description);
        route.setStatus(status);
        deliveryRouteMapper.updateById(route);
        
        // 删除原有路线明细
        deliveryRouteItemMapper.delete(Wrappers.<DeliveryRouteItem>lambdaQuery().eq(DeliveryRouteItem::getRouteId, id));
        
        // 创建新的路线明细
        if (items != null && !items.isEmpty()) {
            for (int i = 0; i < items.size(); i++) {
                Map<String, Object> item = items.get(i);
                Long leaderId = Long.valueOf(item.get("leaderId").toString());
                
                // 检查团长是否存在
                Leader leader = leaderMapper.selectById(leaderId);
                if (leader == null) {
                    throw new BusinessException(ResultCode.DATA_NOT_EXISTED, "团长不存在：ID=" + leaderId);
                }
                
                DeliveryRouteItem routeItem = new DeliveryRouteItem();
                routeItem.setRouteId(id);
                routeItem.setLeaderId(leaderId);
                routeItem.setSequence(i + 1);
                deliveryRouteItemMapper.insert(routeItem);
            }
        }
        
        return ResponseUtil.success();
    }
    
    /**
     * 删除配送路线
     * @param id 路线ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Void>> delete(@PathVariable Long id) {
        DeliveryRoute route = deliveryRouteMapper.selectById(id);
        if (route == null) {
            return ResponseUtil.notFound("配送路线不存在");
        }
        
        // 删除路线明细
        deliveryRouteItemMapper.delete(Wrappers.<DeliveryRouteItem>lambdaQuery().eq(DeliveryRouteItem::getRouteId, id));
        
        // 删除路线
        deliveryRouteMapper.deleteById(id);
        
        return ResponseUtil.success();
    }
    
    /**
     * 更新配送路线状态
     * @param id 路线ID
     * @param status 状态值（0-禁用，1-启用）
     * @return 操作结果
     */
    @PutMapping("/status")
    public ResponseEntity<Result<Void>> updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        DeliveryRoute route = deliveryRouteMapper.selectById(id);
        if (route == null) {
            return ResponseUtil.notFound("配送路线不存在");
        }
        
        DeliveryRoute updateRoute = new DeliveryRoute();
        updateRoute.setId(id);
        updateRoute.setStatus(status);
        deliveryRouteMapper.updateById(updateRoute);
        
        return ResponseUtil.success();
    }
    
    /**
     * 获取可用的团长列表（用于创建路线）
     * @return 团长列表
     */
    @GetMapping("/available-leaders")
    public ResponseEntity<Result<List<Leader>>> getAvailableLeaders() {
        List<Leader> leaders = leaderMapper.selectList(
                Wrappers.<Leader>lambdaQuery()
                        .eq(Leader::getStatus, 1)
                        .orderByAsc(Leader::getName)
        );
        
        return ResponseUtil.success(leaders);
    }

    /**
     * 根据团长ID获取配送路线信息
     * @param leaderId 团长ID
     * @return 路线详情
     */
    @GetMapping("/by-leader/{leaderId}")
    public ResponseEntity<Result<Map<String, Object>>> getRouteByLeaderId(@PathVariable Long leaderId) {
        // 查询团长是否存在
        Leader leader = leaderMapper.selectById(leaderId);
        if (leader == null) {
            return ResponseUtil.notFound("团长不存在");
        }
        
        // 查询团长所属的路线项
        List<DeliveryRouteItem> routeItems = deliveryRouteItemMapper.selectList(
                Wrappers.<DeliveryRouteItem>lambdaQuery()
                        .eq(DeliveryRouteItem::getLeaderId, leaderId)
        );
        
        if (routeItems == null || routeItems.isEmpty()) {
            // 返回空结果而不是404错误
            Map<String, Object> emptyResult = new HashMap<>();
            emptyResult.put("route", null);
            emptyResult.put("items", new ArrayList<>());
            return ResponseUtil.success(emptyResult);
        }
        
        // 使用第一个路线项（如果有多个，优先使用第一个）
        DeliveryRouteItem routeItem = routeItems.get(0);
        
        // 查询路线信息
        DeliveryRoute route = deliveryRouteMapper.selectById(routeItem.getRouteId());
        if (route == null) {
            return ResponseUtil.notFound("配送路线不存在");
        }
        
        // 查询路线明细
        List<DeliveryRouteItem> items = deliveryRouteItemMapper.selectList(
                Wrappers.<DeliveryRouteItem>lambdaQuery()
                        .eq(DeliveryRouteItem::getRouteId, route.getId())
                        .orderByAsc(DeliveryRouteItem::getSequence)
        );
        
        // 查询团长信息
        List<Map<String, Object>> itemsWithLeader = new ArrayList<>();
        for (DeliveryRouteItem item : items) {
            Leader leaderInfo = leaderMapper.selectById(item.getLeaderId());
            if (leaderInfo != null) {
                Map<String, Object> itemMap = new HashMap<>();
                itemMap.put("id", item.getId());
                itemMap.put("leaderId", item.getLeaderId());
                itemMap.put("leaderName", leaderInfo.getName());
                itemMap.put("leaderPhone", leaderInfo.getPhone());
                itemMap.put("leaderAddress", leaderInfo.getAddress());
                itemMap.put("sequence", item.getSequence());
                itemsWithLeader.add(itemMap);
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("route", route);
        result.put("items", itemsWithLeader);
        
        return ResponseUtil.success(result);
    }
} 